// index.js
import peg from "pegjs";
import fs from "fs";
import { generateCode } from "./codegen.js";

// 1. 读取PEG.js语法规则并生成解析器
const grammar = fs.readFileSync("grammar.pegjs", "utf8");
const parser = peg.generate(grammar);

// 2. 读取易语言代码并解析
const easyCode = fs.readFileSync("test.ey", "utf8");
const ast = parser.parse(easyCode);
console.log("==========AST结构===============\n");
console.log('AST结构:', JSON.stringify(ast, null, 2));

// 3. 生成多语言代码
const outputDir = './output';
if (!fs.existsSync(outputDir)) {
  fs.mkdirSync(outputDir, { recursive: true });
}
const languages = ['cpp', 'csharp', 'java'];
languages.forEach(language => {
  const code = generateCode(ast, language);
  const extension = language === 'cpp' ? 'cpp' : 
                    language === 'csharp' ? 'cs' : 
                    language === 'java' ? 'java' : 'txt';
  const outputFile = `${outputDir}/Main.${extension}`;
  fs.writeFileSync(outputFile, code);
  console.log(`===========生成的${language}代码==============\n`);
  console.log(`生成的${language}代码:\n`, code);
  console.log(`已写入文件: ${outputFile}\n`);
});